const router = require('koa-router')()
const { exec } = require('../db/index')
const {
  getBlogsList,
  addBlogsItem,
  updateBlogsItem,
  deleteBlogsItem
} = require('../model/blogs')

const {
  SuccessModel,
  FailModel
} = require('../utils/resModel')

// 路由前缀
router.prefix('/api/blogs')
// 查询博客列表
router.get('/', async(ctx, next) => {
  const data = await getBlogsList()
  ctx.body = new SuccessModel(data, 'success')
})

// 增加 一篇文章
router.post('/', async(ctx, next) => {
  const data = await addBlogsItem({...ctx.request.body})
  ctx.body = new SuccessModel(data.insertId, '新增成功了')
})

// 修改
router.put('/:id', async(ctx, next) => {
  const id = ctx.params.id;
  const data = await updateBlogsItem({id, ...ctx.request.body})
  ctx.body = new SuccessModel(data.affectedRows, '修改成功了')
})
// 删除
router.delete('/:id', async(ctx, next) => {
  const id = ctx.params.id;
  const data = await deleteBlogsItem(id)
  ctx.body = new SuccessModel(data, '删除成功了')
})

// 模糊搜索接口
router.get('/search', async(ctx, next) => {
  const { q } = ctx.query;  // 拿到关键字参数
  console.log(q, 'q')
  const sql = `select * from blogs where title like '%${q}%';`
  const data = await exec(sql)
  ctx.body = new SuccessModel(data, 'success')
})

// 分页接口
router.get('/page', async(ctx, next) => {
  const { page, size } = ctx.query
  const sql = `select * from blogs limit ${page * size}, ${size};`
  const data = await exec(sql)
  if (data.length) {
    ctx.body = new SuccessModel(data, 'success')
  } else {
    ctx.body = new FailModel('请求数据失败了')
  }
})


module.exports = router
